﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;

namespace BoYuan.MvcCodeTemplates.FineUIMvc.Template
{
    public class AddcshtmlTemplate: FineuiBase
    {
        public static string GetCode(TableModel tb)
        {
            List<DbColumnInfo> list = tb.Columns;
            DbColumnInfo keyModel = list.FirstOrDefault(p => p.IsPrimarykey == true);
            if (keyModel == null) { throw new Exception("表没有主键，没办法生成代码！ControllerTemplate"); }

            string defaultValueStr = string.Empty;
            string  formRowStr= GetFormRowCode(tb.Columns, ref defaultValueStr);

            string code = string.Format(@"
@{{
    ViewBag.Title = ""编辑页面"";
    var F = Html.F();
}}

@model {0}.{1}

@section head {{

}}

@section body {{
    @(F.Form().ID(""form_Edit"").ShowHeader(false).ShowBorder(false).AutoScroll(true).BodyPadding(""15px 15px"").IsViewPort(true)
        .Rows(
{3}
           
        )
        .Toolbars(F.Toolbar().Position(ToolbarPosition.Bottom)
            .Items(F.HiddenFieldFor(m=>m.{2}).ID(""f_{2}""), F.ToolbarFill(),
                F.Button().ID(""Button_save"").ValidateForms(""form_Edit"").Text(""保存"").Icon(Icon.SystemSaveNew).OnClick(Url.Action(""Button_save_OnClick""),""form_Edit"")
            )
        ))
}}

@section script {{
     <script>
        F.ready(function () {{
            @if(Request[""id""]==null)
            {{
{4}
            }}
        }})
     </script>
}}
"
            ,tb.ModelName               //0
            ,tb.TableName               //1
            ,keyModel.DbColumnName      //2
            ,formRowStr                 //3
            ,defaultValueStr            //4  
            );
            return code;
        }

        private static string GetFormRowCode(List<DbColumnInfo> clms, ref string defaultValueStr)
        {
            var list = clms.Where(p => p.IsPrimarykey == false).ToList();
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();//生成初始化默认值的代码。
            string f_control_Temp = string.Empty;
            string tempDefaultValueStr = string.Empty;
            for (int i = 0; i < list.Count; i++)
            {
                f_control_Temp = GetFormControl(list[i],ref tempDefaultValueStr);
                sb2.Append(tempDefaultValueStr);
                if (f_control_Temp.Length > 0)
                {
                    sb.AppendLine("             ,F.FormRow().Items(" + f_control_Temp+")");
                }
            }

            defaultValueStr = sb2.ToString();
            return "             " + (sb.ToString().TrimStart().TrimStart(','));
        }
        private static string GetFormControl(DbColumnInfo clm,ref string defaultValueStr)
        {
            string showStr = !clm.IsNullable ? ".Required(true).ShowRedStar(true)" : string.Empty;//是否必填，0不可以为null，1可以为null
            string showName = GetComment(clm.ColumnDescription, clm.DbColumnName);
            string showDefault = GetDefaultValue(clm.DefaultValue);
            defaultValueStr = string.Empty;
            switch (clm.DataType.ToLower())
            {
                case "bit":
                    return "F.CheckBoxFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName + "\").Label(\"" + showName + "\").DisplayType(CheckBoxDisplayType.Switch).ShowSwitchText(true)";

                case "datetime":
                    if (clm.DefaultValue.IndexOf("getdate()", StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        return string.Empty;
                    }
                    else
                    {
                        return "F.DatePickerFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName +
                               "\").DateFormatString(\"yyyy-MM-dd HH:mm:ss\").Label(\"" + showName + "\")" + showStr ;
                    }
                case "bigint"://break;
                case "smallint"://break;
                case "tinyint"://break;
                case "int":
                    defaultValueStr = "                @Html.Raw(\"F.ui.f_"+ clm.DbColumnName + ".setValue('"+ showDefault + "');\");" + Environment.NewLine;
                    return "F.NumberBoxFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName + "\").Label(\"" + showName + "\")" + showStr + ".NoDecimal(true)";

                case "real":// break;
                case "float":// break;
                case "money":// break;
                case "decimal":
                    defaultValueStr = "                @Html.Raw(\"F.ui.f_" + clm.DbColumnName + ".setValue('" + showDefault + "');\");" + Environment.NewLine;
                    return "F.NumberBoxFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName + "\").Label(\"" + showName + "\")" + showStr + ".NoDecimal(false)";
                default:
                    if (clm.PropertyName.ToLower() == "system.string") //字符串类型
                    {
                        if (clm.Length > 0) //TextBox
                        {
                            // 对nvarchar字节的判断，需要除以2；nvarchar 则不需要
                            return "F.TextBoxFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName + "\").Label(\"" + showName + "\")" + showStr + ".MaxLength("
                                   + (clm.DataType.Substring(0, 1).ToLower() == "n" ? clm.Length / 2 : clm.Length) + ")";
                        }
                        else //TextArea
                        {
                            return "F.TextAreaFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName + "\").Label(\"" + showName + "\")" + showStr + ".Height(100)";
                        }
                    }
                    else //未知类型
                    {
                        return "F.TextBoxFor(m=>m." + clm.DbColumnName + ").ID(\"f_" + clm.DbColumnName + "\").Label(\"" + showName + "\")" + showStr ;
                    }
            }
        }
    }
}
